package com.rentong.wx.cust.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.service.WxPayService;
import com.rentong.basic.BusinessException;
import com.rentong.common.RandomUtils;
import com.rentong.config.WxPayProperties;
import com.rentong.wx.cust.dao.*;
import com.rentong.wx.cust.domain.*;
import com.rentong.wx.cust.dto.*;
import com.rentong.wx.cust.service.CustFapiaoApplyService;
import com.rentong.wx.cust.service.CustServiceOrderService;
import com.rentong.wx.sys.dao.SysConfDao;
import com.rentong.wx.sys.dao.SysConfShopTypeDao;
import com.rentong.wx.sys.dao.SysServiceDao;
import com.rentong.wx.sys.domain.SysConfEntity;
import com.rentong.wx.sys.domain.SysConfShopTypeEntity;
import com.rentong.wx.sys.domain.SysServiceEntity;
import com.rentong.wx.utils.GaoDeMapUtil;
import com.rentong.wx.utils.PayStateEnum;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class CustServiceOrderServiceImpl implements CustServiceOrderService {

    @Resource
    private CustServiceOrderDao custServiceOrderDao;

    @Resource
    private CustServiceOrderUrlDao custServiceOrderUrlDao;

    @Resource
    private CustServiceOrderTimeDao custServiceOrderTimeDao;

    @Autowired
    private CustServiceOrderChefDao custServiceOrderChefDao;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private CustAddressDao custAddressDao;

    @Autowired
    private WxCustUserMapper wxCustUserMapper;

    @Autowired
    private SysConfDao sysConfDao;

    @Autowired
    private SysServiceDao sysServiceDao;

    @Autowired
    private CustFapiaoTaitouDao custFapiaoTaitouDao;

    @Autowired
    private CustFapiaoApplyService custFapiaoApplyService;

    @Autowired
    private CustFapiaoApplyDao custFapiaoApplyDao;

    @Autowired
    private CustOrderPayDao custOrderPayDao;

    @Autowired
    private WxPayProperties wxPayProperties;

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private CustOrderPayServiceImpl custOrderPayServiceImpl;

    @Autowired
    private CustFlowDao custFlowDao;

    @Autowired
    private CustFlowTypeDao custFlowTypeDao;

    @Autowired
    private CustServiceOrderAdvDao custServiceOrderAdvDao;

    @Autowired
    private SysConfShopTypeDao sysConfShopTypeDao;

    @Autowired
    private CustUserCaixiDao custUserCaixiDao;

    @Autowired
    private CustUserServiceDao custUserServiceDao;

    @Autowired
    private CustServiceOrderShouhouDao custServiceOrderShouhouDao;

    @Autowired
    private CustServiceOrderPingjiaDao custServiceOrderPingjiaDao;

    @Autowired
    private CustUserServiceTimeDao custUserServiceTimeDao;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public CustServiceOrderEntityDto getOrderByServiceOrderId(CustServiceOrderEntityDto cso) {
        CustServiceOrderEntityDto csod = custServiceOrderDao.getOrderByServiceOrderId(cso);

        if (csod.getOrderState() > 1 && cso.getServiceOrderType() == 1) {
            WxCustUser wc = wxCustUserMapper.selectByPrimaryKey(csod.getChefId());

            if (wc != null) {
                //放入师傅信息
                csod.setServiceAddressDetail(wc.getAddress());
                csod.setServiceNickName(wc.getNickName());
                csod.setServicePhone(wc.getPhone());
                csod.setLongitudeAddr(wc.getLongitude());
                csod.setLatitudeAddr(wc.getLatitude());
            }
        }
        csod.setIsKaipiao(Math.toIntExact(csod.getFapiaoApplyId()));

        //店铺路况引导
        csod.setCustServiceOrderUrlEntityList(custServiceOrderUrlDao.getCustServiceOrderUrlByOrderId(cso.getServiceOrderId()));

        //服务时间
        csod.setCustServiceOrderTimeEntityList(custServiceOrderTimeDao.getServiceOrderTime(cso.getServiceOrderId()));

        //服务与价格中的岗位/套餐信息
        csod.setChefService(sysServiceDao.getServiceProject(csod.getServiceId()));


        if (!"0".equals(csod.getChefId().toString())) {
            //查询出厨师
            WxCustUserDto wcud = wxCustUserMapper.getUserByCustId(csod.getChefId());

            //查询出用户的意向店铺、菜系、服务
            List<SysConfShopTypeEntity> shopTypeList = sysConfShopTypeDao.getShopTypeByIds(wcud.getShopTypeIds());
            List<CustUserCaixiEntityDto> caixiList = custUserCaixiDao.getCaixiByCustId(wcud.getCustId());
            List<CustUserServiceEntityDto> serviceList = custUserServiceDao.getServiceByCustId(wcud.getCustId());

            List<CustUserServiceEntity> shangwuyanqingList = new ArrayList<>();
            List<CustUserServiceEntity> daibanList = new ArrayList<>();

            for (int j = 0; j < serviceList.size(); j++) {
                if (serviceList.get(j).getBigTypeId() == 1L) {
                    //代班服务（到店代厨）
                    daibanList.add(serviceList.get(j));

                } else {
                    //商务宴请（到家私厨）
                    shangwuyanqingList.add(serviceList.get(j));

                }
            }

            //给意向店铺、菜系、商务宴请、代班服务赋值
            //传给前端（每种类型，所有数量都传给了前端，文档里写下，让前端控制每样展示几个）
            wcud.setShopTypeList(shopTypeList);
            wcud.setCaixiList(caixiList);
            wcud.setShangwuyanqingList(shangwuyanqingList);
            wcud.setDaibanList(daibanList);

            //服务与价格中的师傅信息
            csod.setWcu(wcud);
        }


        //如果是“待确认师傅”，需要查询出数量
        if (csod.getOrderState() == 1) {

            if (cso.getServiceOrderType() == 1) {
                //1：订单详情（用户发起查询）
                List<CustServiceOrderChefEntity> list = custServiceOrderChefDao.getCustServiceOrderChefByOrderId(csod.getServiceOrderId());

                if (list != null && list.size() > 0) {
                    csod.setChefNum(list.size());
                    csod.setChefTime(list.get(0).getAddTime());
                } else {
                    csod.setChefNum(0);
                }

            } else {
                //订单详情（师傅发起查询）
//                CustServiceOrderChefEntity csoc = custServiceOrderChefDao.getCustServiceOrderChefByOrderIdAndCustId(csod.getServiceOrderId(), csod.getCustId());
                CustServiceOrderChefEntity csoc = custServiceOrderChefDao.getCustServiceOrderChefByOrderIdAndCustId(csod.getServiceOrderId(), cso.getCustId());
                if (csoc.getServiceOrderChefState() == 3) {
                    csod.setStateNameChef("被拒绝");
                    csod.setOrderState(13);
                }
                csod.setChefTime(csoc.getAddTime());
            }
        }
        if (csod.getOrderState() == 9) {
            csod.setRefuse(custServiceOrderShouhouDao.getShouhouByOrderId(csod.getServiceOrderId()).getRefuse());
        }

        //评价信息
        if (csod.getOrderState() == 6) {
            CustServiceOrderPingjiaEntity custServiceOrderPingjia = custServiceOrderPingjiaDao.getPingJiaByOrderId(cso.getServiceOrderId());
            if (ObjectUtil.isNotEmpty(custServiceOrderPingjia)) {
                CustServiceOrderPingjiaDto custServiceOrderPingjiaDto = new CustServiceOrderPingjiaDto();
                BeanUtils.copyProperties(custServiceOrderPingjia, custServiceOrderPingjiaDto);
                custServiceOrderPingjiaDto.setPingjiaCustId(custServiceOrderPingjia.getCustId());
                custServiceOrderPingjiaDto.setPingjiaChefId(custServiceOrderPingjia.getChefId());
                custServiceOrderPingjiaDto.setPingjiaTime(custServiceOrderPingjia.getAddTime());
                csod.setCustServiceOrderPingjiaDto(custServiceOrderPingjiaDto);
            }
        }

        return csod;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(CustServiceOrderEntity custServiceOrderEntity) {
        custServiceOrderEntity.setOrderState(12);
//        custServiceOrderEntity.setOrderState(7);
//        custServiceOrderEntity.setCancelType(2);
//        custServiceOrderEntity.setCancelTime(new Date());
        custServiceOrderEntity.setUpdateTime(new Date());
        custServiceOrderDao.updateByPrimaryKeySelective(custServiceOrderEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer insertServiceInformation(Long custId, String[] tuArray, Integer[] tuType, ServiceAddressDto serviceAddressDto) {
        serviceAddressDto.setServiceOrderId(Long.parseLong(RandomUtils.getOrderNo()));
        Integer i1 = 0;
        //图片
        for (int i = 0; i < tuArray.length; i++) {
            CustServiceOrderUrlEntity custServiceOrderUrlEntity = new CustServiceOrderUrlEntity();
            custServiceOrderUrlEntity.setOrderUrl(tuArray[i]);
            custServiceOrderUrlEntity.setOrderUrlType(tuType[i]);
            custServiceOrderUrlEntity.setServiceOrderId(serviceAddressDto.getServiceOrderId());
            custServiceOrderUrlEntity.setAddTime(new Date());

            custServiceOrderUrlDao.insertSelective(custServiceOrderUrlEntity);
        }
        //服务信息
        CustServiceOrderEntity custServiceOrderEntity = new CustServiceOrderEntity();
        //保存服务地址信息
        custServiceOrderEntity.setAddTime(new Date());
        custServiceOrderEntity.setServiceNickName(serviceAddressDto.getServiceNickName());
        custServiceOrderEntity.setServiceGender(serviceAddressDto.getServiceGender());
        custServiceOrderEntity.setServicePhone(serviceAddressDto.getServicePhone());
        custServiceOrderEntity.setServiceAddressDetail(serviceAddressDto.getServiceAddressDetail());
        //信息
        custServiceOrderEntity.setCustId(custId);
        custServiceOrderEntity.setOrderType(serviceAddressDto.getOrderType());
        custServiceOrderEntity.setAddAmount(serviceAddressDto.getAddAmount());
        custServiceOrderEntity.setDanjuNo(serviceAddressDto.getDanjuNo());
        custServiceOrderEntity.setPayCustId(serviceAddressDto.getPayCustId());
        custServiceOrderEntity.setServiceId(serviceAddressDto.getServiceId());
        custServiceOrderEntity.setServiceAmount(serviceAddressDto.getAddAmount());
        custServiceOrderEntity.setServiceNum(serviceAddressDto.getServiceNum());
        custServiceOrderEntity.setChefId(serviceAddressDto.getChefId());
        custServiceOrderEntity.setOrderRemark(serviceAddressDto.getOrderRemark());
        custServiceOrderEntity.setServiceOrderId(serviceAddressDto.getServiceOrderId());
        custServiceOrderEntity.setBasePersonNum(serviceAddressDto.getBasePersonNum());
        custServiceOrderEntity.setBaojiaType(serviceAddressDto.getBaojiaType());
        custServiceOrderEntity.setFapiaoApplyId(serviceAddressDto.getFapiaoApplyId());
        custServiceOrderEntity.setPayAmount(serviceAddressDto.getPayAmount());
        custServiceOrderEntity.setTrueAmount(serviceAddressDto.getTrueAmount());
        //不同OrderType
        if (serviceAddressDto.getOrderType() == 1) {
            custServiceOrderEntity.setShopTypeId(serviceAddressDto.getShopTypeId());
            if (serviceAddressDto.getCaiXiId2() == null) {
                custServiceOrderEntity.setCaixiIds(String.valueOf(serviceAddressDto.getCaiXiId1()));
            } else {
                custServiceOrderEntity.setCaixiIds(String.valueOf(serviceAddressDto.getCaiXiId1()) + ',' + String.valueOf(serviceAddressDto.getCaiXiId2()));
            }
            custServiceOrderEntity.setBaojiaAmount(serviceAddressDto.getBaojiaAmount());
        }
        if (serviceAddressDto.getOrderType() == 2) {
            custServiceOrderEntity.setShopTypeId(serviceAddressDto.getShopTypeId());
            if (serviceAddressDto.getCaiXiId2() == null) {
                custServiceOrderEntity.setCaixiIds(String.valueOf(serviceAddressDto.getCaiXiId1()));
            } else {
                custServiceOrderEntity.setCaixiIds(String.valueOf(serviceAddressDto.getCaiXiId1()) + ',' + String.valueOf(serviceAddressDto.getCaiXiId2()));
            }
        }
        if (serviceAddressDto.getOrderType() == 4 || serviceAddressDto.getOrderType() == 5) {
            custServiceOrderEntity.setBasePersonNum(serviceAddressDto.getBasePersonNum());
            custServiceOrderEntity.setTruePersonNum(serviceAddressDto.getTruePersonNum());
            custServiceOrderEntity.setAddAmount(serviceAddressDto.getAddAmount());
        }
        custServiceOrderDao.insertSelective(custServiceOrderEntity);
        //服务时间
        CustServiceOrderTimeEntity custServiceOrderTimeEntity = new CustServiceOrderTimeEntity();
        List<String> serviceOrderDate = serviceAddressDto.getServiceOrderDate();
        Integer[] serviceOrderType = serviceAddressDto.getServiceOrderType();
        String serviceOrderTimeOne = serviceAddressDto.getServiceOrderTimeOne();
        String serviceOrderTimeTwo = serviceAddressDto.getServiceOrderTimeTwo();
        Map<String, String> serviceOrderTimeOneMap = new HashMap<>();
        Map<String, String> serviceOrderTimeTwoMap = new HashMap<>();
        String[] result1 = serviceOrderTimeOne.split(",");
        String[] result2 = serviceOrderTimeTwo.split(",");
        for (int i = 0; i < result1.length; i = i + 2) {
            serviceOrderTimeOneMap.put(result1[i], result1[i + 1]);
        }
        for (int i = 0; i < result2.length; i = i + 2) {
            serviceOrderTimeTwoMap.put(result2[i], result2[i + 1]);
        }
        Integer i = 0;
        for (String item : serviceOrderDate) {
            Integer hourCount = 0;
            custServiceOrderTimeEntity.setAddTime(new Date());
            LocalDate localDate = LocalDate.parse(item);
            Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
            custServiceOrderTimeEntity.setServiceOrderDate(date);
            custServiceOrderTimeEntity.setServiceOrderType(serviceOrderType[i++]);
            custServiceOrderTimeEntity.setServiceOrderId(serviceAddressDto.getServiceOrderId());
            if (serviceOrderTimeOneMap.get(i + "") != null) {
                custServiceOrderTimeEntity.setServiceOrderTimeOne(serviceOrderTimeOneMap.get(i + ""));
            }
            if (serviceOrderTimeOneMap.get(i + "") != null) {
                custServiceOrderTimeEntity.setServiceOrderTimeTwo(serviceOrderTimeTwoMap.get(i + ""));
            }
            if (serviceOrderTimeOneMap.get(i + "") != null) {
                hourCount += 4;
            }
            if (serviceOrderTimeTwoMap.get(i + "") != null) {
                hourCount += 4;
            }
            custServiceOrderTimeEntity.setServiceOrderTimeHour(String.valueOf(hourCount));
            i1 = custServiceOrderTimeDao.insertSelective(custServiceOrderTimeEntity);
        }
        return i1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<CustServiceOrderVo> getCustServiceOrderList(CustServiceOrderDto custServiceOrderDto) {
        List<CustServiceOrderVo> custServiceOrderVos = custServiceOrderTimeDao.getCustServiceOrderList(custServiceOrderDto);
        //是否加急
        Date now = new Date();
        for (CustServiceOrderVo vo : custServiceOrderVos) {
            if (vo.getBstUtilTime() == null || vo.getBstUtilTime().before(now)) {
                vo.setIsUrgent(2); // 不加急
            } else {
                vo.setIsUrgent(1); // 加急
            }
        }

        for (CustServiceOrderVo custServiceOrderVo : custServiceOrderVos) {
            //设置状态
            BigDecimal baojiaAmount = custServiceOrderVo.getBaojiaAmount();
            if (custServiceOrderVo.getChefId() != 0) {
                custServiceOrderVo.setStat(3);
            } else if (custServiceOrderVo.getOrderType() == 2) {
                custServiceOrderVo.setStat(2);
            } else {
                custServiceOrderVo.setStat(1);
            }

            //标题
            if (custServiceOrderVo.getOrderType() == 4 || custServiceOrderVo.getOrderType() == 5) {
                custServiceOrderVo.setPersonNumName(custServiceOrderVo.getTruePersonNum() + "人*" + custServiceOrderVo.getServiceNum() + "桌");
                custServiceOrderVo.setServiceTitle(custServiceOrderVo.getServiceName() + " " + custServiceOrderVo.getPersonNumName());
            } else {
                custServiceOrderVo.setServiceTitle(custServiceOrderVo.getServiceName() + "·" + custServiceOrderVo.getShopTypeName());
            }

//            //设置距离
//            Map map = GaoDeMapUtil.getLonAndLat(custServiceOrderVo.getServiceAddressDetail());
//            String lng = (String) map.get("lng");
//            String lat = (String) map.get("lat");
//            String startLonLat = lng + "," + lat;
//            String endLonLat = custServiceOrderDto.getLongitude() + "," + custServiceOrderDto.getLatitude();
//            double distance = GaoDeMapUtil.getDistance(startLonLat, endLonLat);
//            custServiceOrderVo.setDistance(distance);
        }

        return custServiceOrderVos;

//        //按照距离排序升序
//        if (custServiceOrderDto.getSort() == 2) {
//            custServiceOrderVos.sort((o1, o2) -> Double.compare(o1.getDistance(), o2.getDistance()));
//        }
//
//        // 分页
//        TableDataInfo rspData = new TableDataInfo();
//        int pageNum = custServiceOrderDto.getPageNum();
//        int pageSize = custServiceOrderDto.getPageSize();
//        int total = custServiceOrderVos.size();
//        if ((pageNum - 1) * pageSize >= total) {
//            rspData.setRows(null); // 返回空数据
//            rspData.setTotal(total);
//            return rspData;
//        }
//        int start = (pageNum - 1) * pageSize;
//        int end = Math.min(start + pageSize, total);
//        List<CustServiceOrderVo> pageData = custServiceOrderVos.subList(start, end);
//        rspData.setRows(pageData);
//        rspData.setTotal(total);
//        return rspData;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CusServiceOrderInfoVo getCusServiceOrderInfo(Long serviceOrderId) {
        CusServiceOrderInfoVo cusServiceOrderInfoVo = custServiceOrderTimeDao.getCusServiceOrderInfo(serviceOrderId);
        //标题
        if (cusServiceOrderInfoVo.getBigTypeId() == 1) {
            cusServiceOrderInfoVo.setServiceTitle(cusServiceOrderInfoVo.getServiceName() + "·" + cusServiceOrderInfoVo.getShopTypeName());
        } else {
            cusServiceOrderInfoVo.setPersonNumName(cusServiceOrderInfoVo.getServiceNum() + "桌(" + cusServiceOrderInfoVo.getTruePersonNum() + "人/桌)");
            cusServiceOrderInfoVo.setServiceTitle(cusServiceOrderInfoVo.getServiceName() + " " + cusServiceOrderInfoVo.getTruePersonNum() + "人*" + cusServiceOrderInfoVo.getServiceNum() + "桌");
        }

        //是否加急
        Date now = new Date();
        if (cusServiceOrderInfoVo.getBstUtilTime() == null || cusServiceOrderInfoVo.getBstUtilTime().before(now)) {
            cusServiceOrderInfoVo.setIsUrgent(2); // 不加急
        } else {
            cusServiceOrderInfoVo.setIsUrgent(1); // 加急
        }

        return cusServiceOrderInfoVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<ChefOrderVo> getChefOrderList(Long custId, ChefOrderListDto chefOrderListDto) {
        List<ChefOrderVo> chefOrderVoList = custServiceOrderTimeDao.getChefOrderList(custId, chefOrderListDto.getType(), chefOrderListDto.getPageNum(), chefOrderListDto.getPageSize());

        //师傅待预约的订单
        if (chefOrderListDto.getType() == -1) {
            List<ChefOrderVo> chefOrderVos1 = custServiceOrderTimeDao.getChefOrder(custId, 1);
            List<ChefOrderVo> chefOrderVos2 = custServiceOrderTimeDao.getChefOrder(custId, 3);
            for (ChefOrderVo chefOrderVo : chefOrderVos2) {
                chefOrderVo.setOrderState("13");
            }
            chefOrderVoList.addAll(chefOrderVos1);
            chefOrderVoList.addAll(chefOrderVos2);
        } else if (chefOrderListDto.getType() == 7) {
            List<ChefOrderVo> chefOrderVos2 = custServiceOrderTimeDao.getChefOrder(custId, 3);
            for (ChefOrderVo chefOrderVo : chefOrderVos2) {
                chefOrderVo.setOrderState("13");
            }
            chefOrderVoList.addAll(chefOrderVos2);
        } else if (chefOrderListDto.getType() == 1) {
            List<ChefOrderVo> chefOrderVos1 = custServiceOrderTimeDao.getChefOrder(custId, 1);
            chefOrderVoList.addAll(chefOrderVos1);
        }

        List<ChefOrderVo> subList = chefOrderVoList.stream().skip((chefOrderListDto.getPageNum() - 1) * chefOrderListDto.getPageSize()).limit(chefOrderListDto.getPageSize()).
                collect(Collectors.toList());
        //这里设置订单超时为30分钟
        for (ChefOrderVo chefOrderVo : subList) {
            //剩余时间
            long remainingTime = 0;
            if (chefOrderVo.getOrderState().equals("1")) {
                Instant currentTime = Instant.now();
                Instant time1 = chefOrderVo.getTime1().toInstant();
                Duration duration = Duration.between(time1, currentTime);
                long differenceInMinutes = duration.toMinutes();
                remainingTime = Math.max(0, 30 - differenceInMinutes);
            } else if (chefOrderVo.getOrderType() == 3 || chefOrderVo.getOrderType() == 5) {
                Instant currentTime = Instant.now();
                Instant time1 = chefOrderVo.getTime2().toInstant();
                Duration duration = Duration.between(time1, currentTime);
                long differenceInMinutes = duration.toMinutes();
                remainingTime = Math.max(0, 30 - differenceInMinutes);
            } else if (chefOrderVo.getOrderState().equals("2") || chefOrderVo.getOrderState().equals("5")) {
                Instant currentTime = Instant.now();
                Instant time2 = chefOrderVo.getTime2().toInstant();
                Duration duration = Duration.between(time2, currentTime);
                long differenceInMinutes = duration.toMinutes();
                remainingTime = Math.max(0, 48 * 60 - differenceInMinutes);
            }
            chefOrderVo.setRemainingTime(remainingTime);

            //距离
            String serviceAddressDetail = chefOrderVo.getServiceAddressDetail();
            Map map = GaoDeMapUtil.getLonAndLat(serviceAddressDetail);
            String lng = map.get("lng").toString();
            String lat = map.get("lat").toString();
            String longitude = lng + "," + lat;
            String latitude = chefOrderListDto.getLongitude().toString() + "," + chefOrderListDto.getLatitude().toString();
            double distance = GaoDeMapUtil.getDistance(longitude, latitude);
            distance = distance == 0 ? 0 : Double.parseDouble(String.format("%.1f", distance));
            chefOrderVo.setRange(distance);

            //是否加急
            Date now = new Date();
            if (chefOrderVo.getBstUtilTime() == null || chefOrderVo.getBstUtilTime().before(now)) {
                chefOrderVo.setIsUrgent(2); // 不加急
            } else {
                chefOrderVo.setIsUrgent(1); // 加急
            }

        }
        subList.sort((o1, o2) -> o2.getAddTime().compareTo(o1.getAddTime()));
        return subList;

//        return chefOrderVoList.stream()
//                .filter(item -> item.getRemainingTime() >= 0)
//                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object baojia(baojiaDto baojiaDto, Long custId) {
        //师傅选择了服务地址才能抢单
        WxCustUser wxCustUser = wxCustUserMapper.selectByPrimaryKey(custId);
        if (wxCustUser.getLongitude() == null || wxCustUser.getLatitude() == null) {
            return "未设置服务地址";
        }
        CustServiceOrderChefEntity custServiceOrderChefEntity = new CustServiceOrderChefEntity();
        custServiceOrderChefEntity.setServiceOrderId(baojiaDto.getServiceOrderId());
        custServiceOrderChefEntity.setChefId(custId);
        custServiceOrderChefEntity.setServiceOrderChefState(1);
        custServiceOrderChefEntity.setUpdateTime(new Date());
        custServiceOrderChefEntity.setAddTime(new Date());
        //插入cust_service_order_chef
        if (baojiaDto.getBaojiaType() == 1) {
            if (baojiaDto.getChefBaojiaAmount().compareTo(BigDecimal.ZERO) <= 0) {
                return "报价不正确";
            }
            custServiceOrderChefEntity.setChefBaojiaAmount(baojiaDto.getChefBaojiaAmount());
            custServiceOrderChefDao.save(custServiceOrderChefEntity);
        } else if (baojiaDto.getBaojiaType() == 2) {
            custServiceOrderChefEntity.setChefBaojiaAmount(BigDecimal.valueOf(0));
            custServiceOrderChefDao.save(custServiceOrderChefEntity);
//            CustServiceOrderEntity custServiceOrderEntity = new CustServiceOrderEntity();
        }
        return "操作成功";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirmOrder(Long custId, Long serviceOrderId, Integer type) {
        //type=1为确认，2为拒绝
        //更新订单表
        custServiceOrderDao.updateByServiceOrderId(serviceOrderId, custId, type);
        //更新cust_service_order_chef
        custServiceOrderChefDao.updateByCustId(custId, serviceOrderId, type);
        if (type == 2) {
            CustServiceOrderEntity custServiceOrderEntity = custServiceOrderDao.selectByPrimaryKey(serviceOrderId);
            CustFlowEntity custFlowEntity = new CustFlowEntity();
            if (custServiceOrderEntity.getPayType() == 2) {
                // 微信支付退款处理
                CustOrderPayEntity custOrderPayEntity = custOrderPayDao.getByOrderId(custServiceOrderEntity.getServiceOrderId());
                if (custOrderPayEntity.getPayState() == 7) {
                    throw new BusinessException("订单己取消！");
                }
                Long totalFee = custOrderPayEntity.getPayAmount().longValue(); // 原支付订单金额（单位：分）

                //组装微信退款请求参数
                WxPayRefundRequest refundRequest = new WxPayRefundRequest();
                refundRequest.setOutTradeNo(custOrderPayEntity.getPayId().toString());
                refundRequest.setOutRefundNo(custOrderPayEntity.getOrderId().toString());
                refundRequest.setNotifyUrl(wxPayProperties.getRefundUrl());
                refundRequest.setTotalFee(totalFee.intValue()); // 总金额
                refundRequest.setRefundFee(totalFee.intValue()); // 退款金额
                refundRequest.setOpUserId(wxPayProperties.getMchId());

                //发起退款请求
                try {
                    WxPayRefundResult refundResult = wxPayService.refund(refundRequest);
                    if (!("SUCCESS".equals(refundResult.getResultCode()))) {
                        throw new BusinessException("微信退款失败：" + refundResult.getErrCodeDes());
                    }
                } catch (Exception e) {
                    throw new BusinessException("退款请求失败，请稍后重试！");
                }
            }
            if (custServiceOrderEntity.getPayType() == 3) {
                //余额支付退款处理
                WxCustUser wxCustUser = wxCustUserMapper.selectByPrimaryKey(custId);
                BigDecimal balanceAmount = wxCustUser.getBalanceAmount();
                wxCustUser.setBalanceAmount(balanceAmount.add(custServiceOrderEntity.getTrueAmount()));
                custFlowEntity.setFeeBefore(balanceAmount);
                custFlowEntity.setFeeAfter(balanceAmount.add(custServiceOrderEntity.getTrueAmount()));
                wxCustUserMapper.updateByPrimaryKeySelective(wxCustUser);
            }
            //更新custServiceOrder表
            custServiceOrderEntity.setCancelAmount(custServiceOrderEntity.getTrueAmount());
            custServiceOrderEntity.setOrderState(7);
            custServiceOrderEntity.setCancelType(2);
            custServiceOrderEntity.setCancelTime(new Date());
            custServiceOrderEntity.setUpdateTime(new Date());
            custServiceOrderDao.updateByPrimaryKeySelective(custServiceOrderEntity);

            //新增收支明细
            custFlowEntity.setCustId(custId);
            custFlowEntity.setType(1);
            custFlowEntity.setFlowTypeName("获得退款");
            custFlowEntity.setFlowTypeId(9L);
            custFlowEntity.setFee(custServiceOrderEntity.getTrueAmount());
            custFlowEntity.setServiceOrderId(custServiceOrderEntity.getServiceOrderId());
            custFlowEntity.setAddTime(new Date());
            custFlowDao.insertSelective(custFlowEntity);

            //如果是单点师傅，释放时间
            if (custServiceOrderEntity.getOrderType() == 3 || custServiceOrderEntity.getOrderType() == 5) {
                List<CustServiceOrderTimeEntity> serviceOrderTimeEntities = custServiceOrderTimeDao.getListByOrderId(custServiceOrderEntity.getServiceOrderId());
                if (CollectionUtil.isNotEmpty(serviceOrderTimeEntities)) {
                    for (CustServiceOrderTimeEntity serviceOrderTimeEntity : serviceOrderTimeEntities) {
                        CustUserServiceTimeEntity custUserServiceTime = custUserServiceTimeDao.selectByServiceDate(serviceOrderTimeEntity.getServiceOrderDate(), custServiceOrderEntity.getChefId());
                        if (ObjectUtil.isNotEmpty(custUserServiceTime)) {
                            if (custUserServiceTime.getMorningFabu() == 3) {
                                custUserServiceTime.setMorningFabu(1);
                            }
                            if (custUserServiceTime.getAfternoonFabu() == 3) {
                                custUserServiceTime.setAfternoonFabu(1);
                            }
                            if (custUserServiceTime.getNightFabu() == 3) {
                                custUserServiceTime.setNightFabu(1);
                            }
                            custUserServiceTime.setUpdateTime(new Date());
                            custUserServiceTimeDao.updateByPrimaryKeySelective(custUserServiceTime);
                        }
                    }
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<ServiceOrderChefVo> getOrderChefList(Long serviceOrderId, BigDecimal longitude, BigDecimal latitude) {
        List<ServiceOrderChefVo> serviceOrderChefVoList = custServiceOrderDao.getOrderChefList(serviceOrderId);
        CustServiceOrderEntity custServiceOrderEntity = custServiceOrderDao.selectByPrimaryKey(serviceOrderId);
        if (ObjectUtil.isNotEmpty(serviceOrderChefVoList)) {

            for (ServiceOrderChefVo serviceOrderChefVo : serviceOrderChefVoList) {
                if (custServiceOrderEntity.getBaojiaType() == null) {
                    serviceOrderChefVo.setChefBaojiaAmount(custServiceOrderEntity.getTrueAmount());
                } else if (custServiceOrderEntity.getBaojiaType() == 1) {
                    serviceOrderChefVo.setChefBaojiaAmount(custServiceOrderEntity.getBaojiaAmount());
                }
                //设置距离
                String startLonLat = longitude + "," + latitude;
                String endLonLat = serviceOrderChefVo.getLongitude() + "," + serviceOrderChefVo.getLatitude();
                double distance = GaoDeMapUtil.getDistance(startLonLat, endLonLat);
                distance = distance == 0 ? 0 : Double.parseDouble(String.format("%.1f", distance));
                serviceOrderChefVo.setRange(distance);
                //剩余时间
                serviceOrderChefVo.setRemainingTime(30 - serviceOrderChefVo.getRemainingTime());


                //查询出用户的意向店铺、菜系、服务
                List<SysConfShopTypeEntity> shopTypeList = sysConfShopTypeDao.getShopTypeByIds(serviceOrderChefVo.getShopTypeIds());
                List<CustUserCaixiEntityDto> caixiList = custUserCaixiDao.getCaixiByCustId(serviceOrderChefVo.getCustId());
                List<CustUserServiceEntityDto> serviceList = custUserServiceDao.getServiceByCustId(serviceOrderChefVo.getCustId());

                List<CustUserServiceEntity> shangwuyanqingList = new ArrayList<>();
                List<CustUserServiceEntity> daibanList = new ArrayList<>();

                for (int j = 0; j < serviceList.size(); j++) {
                    if (serviceList.get(j).getBigTypeId() == 1L) {
                        //代班服务（到店代厨）
                        daibanList.add(serviceList.get(j));

                    } else {
                        //商务宴请（到家私厨）
                        shangwuyanqingList.add(serviceList.get(j));

                    }
                }

                //给意向店铺、菜系、商务宴请、代班服务赋值
                //传给前端（每种类型，所有数量都传给了前端，文档里写下，让前端控制每样展示几个）
                serviceOrderChefVo.setShopTypeList(shopTypeList);
                serviceOrderChefVo.setCaixiList(caixiList);
                serviceOrderChefVo.setShangwuyanqingList(shangwuyanqingList);
                serviceOrderChefVo.setDaibanList(daibanList);

            }
        }

        return serviceOrderChefVoList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void startService(StartServiceDto startServiceDto, Long custId) {
        CustServiceOrderEntity custServiceOrderEntity = new CustServiceOrderEntity();
        custServiceOrderEntity.setServiceOrderId(startServiceDto.getServiceOrderId());
        CustServiceOrderEntity orderEntity = custServiceOrderDao.selectByPrimaryKey(startServiceDto.getServiceOrderId());
        if (startServiceDto.getType() == 1) {
            if (orderEntity.getOrderState() != 3) {
                return;
            }
            //开始服务
            custServiceOrderEntity.setStartDakaTime(new Date());
            custServiceOrderEntity.setStartDakaPosition(startServiceDto.getDakaPosition());
            custServiceOrderEntity.setStartDakaRemark(startServiceDto.getDakaRemark());
            custServiceOrderEntity.setStartDakaUrlOne(startServiceDto.getDakaUrlOne());
            custServiceOrderEntity.setStartDakaUrlTwo(startServiceDto.getDakaUrlTwo());
            custServiceOrderEntity.setStartDakaUrlThree(startServiceDto.getDakaUrlThree());
            custServiceOrderEntity.setOrderState(4);
            custServiceOrderEntity.setUpdateTime(new Date());
        } else if (startServiceDto.getType() == 2) {
            if (orderEntity.getOrderState() != 4) {
                return;
            }
            //结束服务
            custServiceOrderEntity.setEndDakaTime(new Date());
            custServiceOrderEntity.setEndDakaPosition(startServiceDto.getDakaPosition());
            custServiceOrderEntity.setEndDakaRemark(startServiceDto.getDakaRemark());
            custServiceOrderEntity.setEndDakaUrlOne(startServiceDto.getDakaUrlOne());
            custServiceOrderEntity.setEndDakaUrlTwo(startServiceDto.getDakaUrlTwo());
            custServiceOrderEntity.setEndDakaUrlThree(startServiceDto.getDakaUrlThree());
            custServiceOrderEntity.setOrderState(5);
            custServiceOrderEntity.setUpdateTime(new Date());
        }
        custServiceOrderDao.updateByPrimaryKeySelective(custServiceOrderEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<CustServiceOrderEntityDto> getUserOrderList(CustServiceOrderEntityDto custServiceOrderEntityDto) {
        List<CustServiceOrderEntityDto> list = custServiceOrderDao.getUserOrderList(custServiceOrderEntityDto);

        for (int i = 0; i < list.size(); i++) {
            List<CustServiceOrderTimeEntity> csotLists = custServiceOrderTimeDao.getServiceOrderTime(list.get(i).getServiceOrderId());
            list.get(i).setCustServiceOrderTimeEntityList(csotLists);
            list.get(i).setIsKaipiao(Math.toIntExact(list.get(i).getFapiaoApplyId()));
            if (list.get(i).getOrderState() == 6) {
                CustServiceOrderPingjiaEntity custServiceOrderPingjia = custServiceOrderPingjiaDao.getPingJiaByOrderId(list.get(i).getServiceOrderId());
                if (ObjectUtil.isNotEmpty(custServiceOrderPingjia)) {
                    CustServiceOrderPingjiaDto custServiceOrderPingjiaDto = new CustServiceOrderPingjiaDto();
                    BeanUtils.copyProperties(custServiceOrderPingjia, custServiceOrderPingjiaDto);
                    custServiceOrderPingjiaDto.setPingjiaCustId(custServiceOrderPingjia.getCustId());
                    custServiceOrderPingjiaDto.setPingjiaChefId(custServiceOrderPingjia.getChefId());
                    custServiceOrderPingjiaDto.setPingjiaTime(custServiceOrderPingjia.getAddTime());
                    list.get(i).setCustServiceOrderPingjiaDto(custServiceOrderPingjiaDto);
                }
            }
            if (!"0".equals(list.get(i).getChefId().toString())) {
                //查询出厨师
                WxCustUserDto wcud = wxCustUserMapper.getUserByCustId(list.get(i).getChefId());

                //查询出用户的意向店铺、菜系、服务
                List<SysConfShopTypeEntity> shopTypeList = sysConfShopTypeDao.getShopTypeByIds(wcud.getShopTypeIds());
                List<CustUserCaixiEntityDto> caixiList = custUserCaixiDao.getCaixiByCustId(wcud.getCustId());
                List<CustUserServiceEntityDto> serviceList = custUserServiceDao.getServiceByCustId(wcud.getCustId());

                List<CustUserServiceEntity> shangwuyanqingList = new ArrayList<>();
                List<CustUserServiceEntity> daibanList = new ArrayList<>();

                for (int j = 0; j < serviceList.size(); j++) {
                    if (serviceList.get(j).getBigTypeId() == 1L) {
                        //代班服务（到店代厨）
                        daibanList.add(serviceList.get(j));

                    } else {
                        //商务宴请（到家私厨）
                        shangwuyanqingList.add(serviceList.get(j));

                    }
                }

                //给意向店铺、菜系、商务宴请、代班服务赋值
                //传给前端（每种类型，所有数量都传给了前端，文档里写下，让前端控制每样展示几个）
                wcud.setShopTypeList(shopTypeList);
                wcud.setCaixiList(caixiList);
                wcud.setShangwuyanqingList(shangwuyanqingList);
                wcud.setDaibanList(daibanList);

                //服务与价格中的师傅信息
                list.get(i).setWcu(wcud);
            }


            //如果是“待确认师傅”，需要查询出数量
            if (list.get(i).getOrderState() == 1) {
                //1：订单详情（用户发起查询）
                List<CustServiceOrderChefEntity> listChef = custServiceOrderChefDao.getCustServiceOrderChefByOrderId(list.get(i).getServiceOrderId());

                if (listChef != null && listChef.size() > 0) {
                    list.get(i).setChefNum(listChef.size());
                    list.get(i).setChefTime(listChef.get(0).getAddTime());
                } else {
                    list.get(i).setChefNum(0);
                }
            }
        }
        return list;
    }


    //订单类型；1：到店代厨·商家报价（DDSJBJ）；2：到店代厨·师傅报价（DDSFBJ）；3：到店代厨·单点师傅（DDDDSF）；
    // 4：到家私厨·项目预约（DJXMYY）；5：到家私厨·单点师傅（DJDDSF）
    private String[] danjuNoHead = {"DDSJBJ", "DDSFBJ", "DDDDSF", "DJXMYY", "DJDDSF"};

    //确认支付按钮
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object insertOrder(CustServiceOrderEntityDto csoe) throws Exception {

        //判断下，地址是否还存在
        CustAddressEntity custAddressEntity = custAddressDao.selectByPrimaryKey(csoe.getAddressId());
        if (custAddressEntity == null) {
            throw new BusinessException("当前地址不存在！");
        }

        //如果是余额支付，需要看下余额是否够
        if (csoe.getPayType() != null && csoe.getPayType() == 3) {
            WxCustUser wxCustUser = wxCustUserMapper.selectByPrimaryKey(csoe.getCustId());
            if (wxCustUser.getBalanceAmount().compareTo(csoe.getPayAmount()) < 0) {
//                throw new BusinessException("余额不足！");
                return "余额不足！";
            }
        }

        //判断下服务是否可用
        SysServiceEntity sysServiceEntity = sysServiceDao.selectByPrimaryKey(csoe.getServiceId());
        if (sysServiceEntity == null) {
            throw new BusinessException("该服务不可用！");
        }


        //生成预支付订单
        Long payId = Long.parseLong(RandomUtils.getPaymentNo());

        //生成订单
        CustServiceOrderEntity cso = new CustServiceOrderEntity();
        Long orderNo = Long.parseLong(RandomUtils.getOrderNo());
        cso.setServiceOrderId(orderNo);
        cso.setDanjuNo(danjuNoHead[csoe.getOrderType() - 1] + orderNo);
        cso.setOrderType(csoe.getOrderType());
        cso.setCustId(csoe.getCustId());
        cso.setPayCustId(csoe.getCustId());
        cso.setServiceId(csoe.getServiceId());
        cso.setServiceNickName(custAddressEntity.getNickName());
        cso.setServiceGender(custAddressEntity.getGender());
        cso.setServicePhone(custAddressEntity.getPhone());
        cso.setServiceAddressDetail(custAddressEntity.getAddressPosition() + custAddressEntity.getAddressDetail());
        cso.setLongitudeAddr(custAddressEntity.getLongitudeAddr());
        cso.setLatitudeAddr(custAddressEntity.getLatitudeAddr());
        cso.setCityId(csoe.getCityId());
        cso.setTotalServiceOrderTime(csoe.getTotalServiceOrderTime());
        cso.setPayAmount(csoe.getPayAmount());
        cso.setPayType(csoe.getPayType());
        cso.setOrderState(12);  //待支付
        cso.setOrderRemark(csoe.getOrderRemark());
        cso.setShareCustId(csoe.getShareCustId());
        cso.setPayId(payId);
        cso.setUpdateTime(new Date());
        cso.setAddTime(new Date());


        //单点师傅，需要录入师傅的custId
        if (csoe.getOrderType() == 3 || csoe.getOrderType() == 5) {
            cso.setChefId(csoe.getChefId());
            //单点师傅时，状态默认为待接单
        }

        //店铺类型、菜系、报价
        if (csoe.getOrderType() == 1 || csoe.getOrderType() == 2) {
            //店铺类型
            cso.setShopTypeId(csoe.getShopTypeId());
            //菜系
            cso.setCaixiIds(csoe.getCaixiIds());
            //报价
            cso.setBaojiaType(csoe.getBaojiaType());
            cso.setBaojiaAmount(csoe.getBaojiaAmount());
        }

        //平台抽成比例
        SysConfEntity s1 = sysConfDao.selectByPrimaryKey(14L);
        cso.setPingtaiBili(new BigDecimal(s1.getConfContent()));
        //分享赚的比例
        SysConfEntity s2 = sysConfDao.selectByPrimaryKey(15L);
        cso.setShareBili(new BigDecimal(s2.getConfContent()));


        //数量（orderType为1、2、3的时，表示天数。为4、5时，表示桌数）
        cso.setServiceNum(csoe.getServiceNum());
        cso.setServiceAmount(csoe.getServiceAmount());

        if (csoe.getOrderType() == 4 || csoe.getOrderType() == 5) {
            //套餐内，每桌的基础人数（orderType为4、5的时候，这里需要传）
            cso.setBasePersonNum(csoe.getBasePersonNum());

            //实际的，每桌的基础人数（orderType为4、5的时候，这里需要传）
            cso.setTruePersonNum(csoe.getTruePersonNum());

            //每加1人，增加的价格（order_type为4、5的时候，这里需要传）
            cso.setAddAmount(csoe.getAddAmount());

            //数量（order_type为4、5时，天数）
            cso.setServiceNum2(csoe.getServiceNum2());
        }

        //是否需要开票。0表示不需要开票，需要开票的话，传fapiaoTaitouId
        if (csoe.getIsKaipiao() != 0) {
            CustFapiaoTaitouEntity cft = custFapiaoTaitouDao.selectByPrimaryKey(Long.parseLong(csoe.getIsKaipiao().toString()));

            CustFapiaoApplyEntityDto custFapiaoApplyEntityDto = new CustFapiaoApplyEntityDto();
            custFapiaoApplyEntityDto.setFapiaoTaitouId(cft.getFapiaoTaitouId());
            custFapiaoApplyEntityDto.setFapiaoAmount(csoe.getPayAmount());
            custFapiaoApplyEntityDto.setServiceOrderId(orderNo);
            custFapiaoApplyEntityDto.setCustId(csoe.getCustId());
            int num = custFapiaoApplyService.insertFapiaoApply(custFapiaoApplyEntityDto);

            if (num > 0) {
                CustFapiaoApplyEntity csa = custFapiaoApplyDao.getFapiaoApplyByOrderId(orderNo);
                cso.setFapiaoApplyId(csa.getFapiaoApplyId());
            }
        }


        //录入下单的图片/视频的表
        if (csoe.getOrderUrl() != null && csoe.getOrderUrl().length() > 0) {
            String[] orderUrl = csoe.getOrderUrl().split(",");

            for (int i = 0; i < orderUrl.length; i++) {
                CustServiceOrderUrlEntity csou = new CustServiceOrderUrlEntity();
                csou.setServiceOrderId(orderNo);
                csou.setOrderUrl(orderUrl[i]);
                csou.setAddTime(new Date());
                custServiceOrderUrlDao.insertSelective(csou);
            }
        }


        //录入订单的服务时间的表
        String[] serviceStr = csoe.getServiceStr().split(",");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        for (int i = 0; i < serviceStr.length; i++) {
            String[] strTemp = serviceStr[i].split("、");

            CustServiceOrderTimeEntity csot = new CustServiceOrderTimeEntity();
            csot.setServiceOrderId(orderNo);
            csot.setServiceOrderDate(sdf.parse(strTemp[0]));
            csot.setServiceOrderType(Integer.parseInt(strTemp[1]));
            csot.setServiceOrderTimeOne(strTemp[3]);

            //全天的话，有两段时间
            if (csot.getServiceOrderType() == 4) {
                csot.setServiceOrderTimeTwo(strTemp[4]);
            }
            csot.setServiceOrderTimeHour(strTemp[2]);

            csot.setAddTime(new Date());
            custServiceOrderTimeDao.insertSelective(csot);

            if (csoe.getOrderType() == 3 || csoe.getOrderType() == 5) {
                //单点师傅的订单
                custUserServiceTimeDao.updateFabuByCustIdAndDate(Integer.parseInt(strTemp[1]), csoe.getChefId(), sdf.parse(strTemp[0]));
            }

        }

        if (csoe.getOrderType() == 1 || csoe.getOrderType() == 2) {
            //非单点师傅时，状态默认为待预约
            cso.setOrderState(1);
        }

        //订单表数据入库
        custServiceOrderDao.insertSelective(cso);


        //1：到店代厨·商家报价；2：到店代厨·师傅报价；
        //不需要支付，直接返回
        if (csoe.getOrderType() == 1 || csoe.getOrderType() == 2) {
            return null;
        }

        //zhifu为2：找人代付
        //不需要支付，直接返回
        if (csoe.getZhifu() == 2) {
            return cso;
        }

        return toPay(csoe.getPayType(), csoe.getCustId(), orderNo, payId);
    }

    //代付按钮
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object daifuOrder(CustServiceOrderEntityDto csoe) throws Exception {
        CustServiceOrderEntity cso1 = custServiceOrderDao.selectByPrimaryKey(csoe.getServiceOrderId());

        //如果是余额支付，需要看下余额是否够
        if (csoe.getPayType() == 3) {
            WxCustUser wxCustUser = wxCustUserMapper.selectByPrimaryKey(csoe.getCustId());

            if (wxCustUser.getBalanceAmount().compareTo(cso1.getPayAmount()) < 0) {
                return "余额不足！";
            }
        }

        CustServiceOrderEntity cso = new CustServiceOrderEntity();

        //生成预支付订单
        Long payId = Long.parseLong(RandomUtils.getPaymentNo());

        cso.setServiceOrderId(csoe.getServiceOrderId());
        cso.setPayCustId(csoe.getCustId());
        cso.setPayType(csoe.getPayType());
        cso.setPayId(payId);
        cso.setUpdateTime(new Date());
        custServiceOrderDao.updateByPrimaryKeySelective(cso);

        return toPay(csoe.getPayType(), csoe.getCustId(), csoe.getServiceOrderId(), payId);
    }


    //支付下单接口（根据payType哪种类型的支付）
    //1：支付宝，2：微信；3：余额
    public Object toPay(Integer payType, Long custId, Long serviceOrderId, Long payId) throws Exception {
        //获取用户信息
        WxCustUser custUserEntity = wxCustUserMapper.selectByPrimaryKey(custId);

        //查询历史支付信息
        List<Integer> stateList = new ArrayList<>(2);
        stateList.add(PayStateEnum.PAYING.getState());
        stateList.add(PayStateEnum.PAY_SUCCESS.getState());
        List<CustOrderPayEntity> orderPayList = custOrderPayDao.getOrderPaid(custId, payId, stateList);
        if (orderPayList != null && orderPayList.size() > 0) {
            throw new BusinessException("当前订单已经支付，请前往订单查看");
        }

        //获取订单信息
        BigDecimal payAmount = new BigDecimal("0");
        if (serviceOrderId.toString().length() == 19) {
            //长度为19位，下单的是普通订单
            CustServiceOrderEntity custServiceOrderEntity = custServiceOrderDao.selectByPrimaryKey(serviceOrderId);
            payAmount = custServiceOrderEntity.getPayAmount();

        } else if (serviceOrderId.toString().length() == 18) {
            //其他订单（电话、充值等）
            CustServiceOrderAdvEntity custServiceOrderAdvEntity = custServiceOrderAdvDao.selectByPrimaryKey(serviceOrderId);
            payAmount = custServiceOrderAdvEntity.getPayAmount();

        } else {
            throw new BusinessException("支付异常！");
        }

        CustOrderPayEntity custOrderPayEntity = new CustOrderPayEntity();
        custOrderPayEntity.setPayId(payId);
        custOrderPayEntity.setOrderId(serviceOrderId);
        custOrderPayEntity.setCustId(custId);
        custOrderPayEntity.setOrderAmount(payAmount);
        custOrderPayEntity.setPayState(PayStateEnum.NOT_PAY.getState());
        custOrderPayEntity.setPayAmount(payAmount);
        custOrderPayEntity.setPayType(payType);

        Object payRetObj = null;
        if (payType == 1) {
            System.out.println("=============支付宝支付=============");
        } else if (payType == 2) {
            System.out.println("=============微信小程序中，微信支付=============");

            try {
                //微信支付，支付向微信下单（小程序）
                //组装微信请求参数
                WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
                orderRequest.setBody(wxPayProperties.getBody() + "[" + serviceOrderId + "]");
                orderRequest.setOutTradeNo(custOrderPayEntity.getPayId().toString());
                orderRequest.setTotalFee(payAmount.intValue());
                orderRequest.setOpenid(custUserEntity.getOpenId());
                orderRequest.setSpbillCreateIp("127.0.0.1");
                orderRequest.setTradeType("JSAPI");
                orderRequest.setNotifyUrl(wxPayProperties.getNotifyUrl());

                WxPayMpOrderResult wxPayMpOrderResult = wxPayService.createOrder(orderRequest);
                custOrderPayEntity.setPrepayId(wxPayMpOrderResult.getPackageValue().replaceAll("prepay_id=", ""));

                WxCustPayInfo custPayInfo = new WxCustPayInfo();
                BeanUtils.copyProperties(wxPayMpOrderResult, custPayInfo);
                custPayInfo.setPayId(payId);
                custPayInfo.setServiceOrderId(serviceOrderId);
                payRetObj = custPayInfo;

            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }

        } else if (payType == 3) {
            //3：余额，扣减余额

            //不是免费的单子
            if (!payAmount.toString().equals("0")) {
                WxCustUser wxCustUser = wxCustUserMapper.selectByPrimaryKey(custId);
                if (wxCustUser.getBalanceAmount().compareTo(payAmount) < 0) {
                    return "余额不足！";
                }
                WxCustUser wc = new WxCustUser();
                wc.setCustId(wxCustUser.getCustId());
                wc.setBalanceAmount(wxCustUser.getBalanceAmount().subtract(payAmount));
                wc.setUpdateTime(new Date());
                wxCustUserMapper.updateByPrimaryKeySelective(wc);

                //记录消费流水
                CustFlowTypeEntity cft = custFlowTypeDao.selectByPrimaryKey(4L);

                CustFlowEntity custFlowEntity = new CustFlowEntity();
                custFlowEntity.setCustId(custId);
                custFlowEntity.setType(cft.getType());
                custFlowEntity.setFlowTypeName(cft.getFlowTypeName());
                custFlowEntity.setFlowTypeId(cft.getFlowTypeId());
                custFlowEntity.setFee(payAmount);
                custFlowEntity.setFeeBefore(wxCustUser.getBalanceAmount());
                custFlowEntity.setFeeAfter(wc.getBalanceAmount());
                custFlowEntity.setServiceOrderId(serviceOrderId);
                custFlowEntity.setAddTime(new Date());
                custFlowDao.insertSelective(custFlowEntity);
            }


            //支付回调，处理业务（这里是余额调用）
            custOrderPayServiceImpl.alipayAndweixinNotify(serviceOrderId);

            WxCustPayInfo custPayInfo = new WxCustPayInfo();
            custPayInfo.setServiceOrderId(serviceOrderId);
            payRetObj = custPayInfo;

            return null;
        } else {
            throw new BusinessException("支付异常！");
        }

        custOrderPayEntity.setPayState(PayStateEnum.PAYING.getState());
        custOrderPayDao.insertSelective(custOrderPayEntity);

        return payRetObj;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String cancelOrder(UpdateOrderDto updateOrderDto, Long userId) {
        CustServiceOrderEntity custServiceOrderEntity = custServiceOrderDao.selectByPrimaryKey(updateOrderDto.getServiceOrderId());
        if (custServiceOrderEntity.getTrueAmount().equals(BigDecimal.ZERO)) {
            //没有支付

            //更新cust_service_order
            CustServiceOrderEntity custServiceOrderEntityUpdate = new CustServiceOrderEntity();
            custServiceOrderEntityUpdate.setServiceOrderId(updateOrderDto.getServiceOrderId());
            custServiceOrderEntityUpdate.setOrderState(7);
            custServiceOrderEntityUpdate.setCancelType(2);
            custServiceOrderEntityUpdate.setCancelTime(new Date());
            custServiceOrderEntityUpdate.setUpdateTime(new Date());
            custServiceOrderDao.updateByPrimaryKeySelective(custServiceOrderEntityUpdate);
        } else {
            //己支付

            //如果没有选择师傅，全退，如果选择了师傅，服务前30分钟之外取消退还100%，服务前0-30分钟取消退还30%
            BigDecimal refundAmount = BigDecimal.ZERO;
            BigDecimal trueAmount = custServiceOrderEntity.getTrueAmount();
            if (custServiceOrderEntity.getChefId() == 0 || custServiceOrderEntity.getOrderType() == 3 || custServiceOrderEntity.getOrderType() == 5) {
                refundAmount = trueAmount;
            } else {
                //获取服务时间
                List<CustServiceOrderTimeEntity> orderTimes = custServiceOrderTimeDao.getListByOrderId(updateOrderDto.getServiceOrderId());
                if (CollectionUtil.isNotEmpty(orderTimes)) {
                    List<LocalDateTime> localDateTimes = new ArrayList<>();
                    for (CustServiceOrderTimeEntity orderTime : orderTimes) {
                        LocalDate date = LocalDate.parse(orderTime.getServiceOrderDate().toString());
                        String startTimeStr = orderTime.getServiceOrderTimeOne().split("-")[0];
                        LocalDateTime dateTime = LocalDateTime.of(date, LocalTime.parse(startTimeStr));
                        localDateTimes.add(dateTime);
                    }
                    //最小的过期时间
                    LocalDateTime currentTime = LocalDateTime.now();
                    OptionalLong minMinutes = localDateTimes.stream()
                            .mapToLong(dateTime ->
                                    Duration.between(currentTime, dateTime).toMinutes()
                            )
                            .min();

                    if (minMinutes.isPresent()) {
                        if (minMinutes.getAsLong() > 30) {
                            refundAmount = trueAmount;
                        } else {
                            refundAmount = trueAmount.multiply(new BigDecimal("0.3"));
                        }
                    }
                }
            }
            Integer payType = custServiceOrderEntity.getPayType();
            CustFlowEntity custFlowEntity = new CustFlowEntity();

            if (payType == 2) {
                // 微信支付退款处理
                CustOrderPayEntity custOrderPayEntity = custOrderPayDao.getByOrderId(updateOrderDto.getServiceOrderId());
                if (custOrderPayEntity.getPayState() == 7) {
                    throw new BusinessException("订单己取消！");
                }
                Long totalFee = custOrderPayEntity.getPayAmount().longValue(); // 原支付订单金额（单位：分）
                Long refundFee = refundAmount.longValue(); // 退款金额（单位：分）

                //组装微信退款请求参数
                WxPayRefundRequest refundRequest = new WxPayRefundRequest();
                refundRequest.setOutTradeNo(custOrderPayEntity.getPayId().toString());
                refundRequest.setOutRefundNo(custOrderPayEntity.getOrderId().toString());
                refundRequest.setNotifyUrl(wxPayProperties.getRefundUrl());
                refundRequest.setTotalFee(totalFee.intValue()); // 总金额
                refundRequest.setRefundFee(refundFee.intValue()); // 退款金额
                refundRequest.setOpUserId(wxPayProperties.getMchId());

                //发起退款请求
                try {
                    WxPayRefundResult refundResult = wxPayService.refund(refundRequest);
                    if (!("SUCCESS".equals(refundResult.getResultCode()))) {
                        throw new BusinessException("微信退款失败：" + refundResult.getErrCodeDes());
                    }
                } catch (Exception e) {
                    throw new BusinessException("退款请求失败，请稍后重试！");
                }
            }
            if (payType == 3) {
                //余额支付退款处理
                WxCustUser wxCustUser = wxCustUserMapper.selectByPrimaryKey(custServiceOrderEntity.getPayCustId());
                BigDecimal balanceAmount = wxCustUser.getBalanceAmount();
                wxCustUser.setBalanceAmount(balanceAmount.add(refundAmount));
                custFlowEntity.setFeeBefore(balanceAmount);
                custFlowEntity.setFeeAfter(balanceAmount.add(refundAmount));
                wxCustUserMapper.updateByPrimaryKeySelective(wxCustUser);
            }
            //更新custServiceOrder表
            custServiceOrderEntity.setCancelAmount(refundAmount);
            custServiceOrderEntity.setOrderState(7);
            custServiceOrderEntity.setCancelType(2);
            custServiceOrderEntity.setCancelTime(new Date());
            custServiceOrderEntity.setUpdateTime(new Date());
            custServiceOrderDao.updateByPrimaryKeySelective(custServiceOrderEntity);

            //新增收支明细
            custFlowEntity.setCustId(custServiceOrderEntity.getPayCustId());
            custFlowEntity.setType(1);
            custFlowEntity.setFlowTypeName("获得退款");
            custFlowEntity.setFlowTypeId(9L);
            custFlowEntity.setFee(refundAmount);
            custFlowEntity.setServiceOrderId(updateOrderDto.getServiceOrderId());
            custFlowEntity.setAddTime(new Date());
            custFlowDao.insert(custFlowEntity);

            //如果是单点师傅，释放时间
            if (custServiceOrderEntity.getOrderType() == 3 || custServiceOrderEntity.getOrderType() == 5) {
                List<CustServiceOrderTimeEntity> serviceOrderTimeEntities = custServiceOrderTimeDao.getListByOrderId(custServiceOrderEntity.getServiceOrderId());
                if (CollectionUtil.isNotEmpty(serviceOrderTimeEntities)) {
                    for (CustServiceOrderTimeEntity serviceOrderTimeEntity : serviceOrderTimeEntities) {
                        CustUserServiceTimeEntity custUserServiceTime = custUserServiceTimeDao.selectByServiceDate(serviceOrderTimeEntity.getServiceOrderDate(), custServiceOrderEntity.getChefId());
                        if (ObjectUtil.isNotEmpty(custUserServiceTime)) {
                            if (custUserServiceTime.getMorningFabu() == 3) {
                                custUserServiceTime.setMorningFabu(1);
                            }
                            if (custUserServiceTime.getAfternoonFabu() == 3) {
                                custUserServiceTime.setAfternoonFabu(1);
                            }
                            if (custUserServiceTime.getNightFabu() == 3) {
                                custUserServiceTime.setNightFabu(1);
                            }
                            custUserServiceTime.setUpdateTime(new Date());
                            custUserServiceTimeDao.updateByPrimaryKeySelective(custUserServiceTime);
                        }
                    }
                }
            }
        }
        return "取消成功";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refuseChef(UpdateOrderDto updateOrderDto) {
        CustServiceOrderChefEntity chefEntity = new CustServiceOrderChefEntity();
        chefEntity.setChefId(updateOrderDto.getChefId());
        chefEntity.setServiceOrderId(updateOrderDto.getServiceOrderId());
        chefEntity.setServiceOrderChefState(3);
        chefEntity.setUpdateTime(new Date());
        custServiceOrderChefDao.updateStat(chefEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object chooseChef(UpdateOrderDto updateOrderDto) {

        Map<String, Object> params = new HashMap<>();
        params.put("serviceOrderId", updateOrderDto.getServiceOrderId());
        params.put("chefId", updateOrderDto.getChefId());
        custServiceOrderChefDao.updateServiceOrderChefState(params);

        CustServiceOrderEntity custServiceOrder = new CustServiceOrderEntity();
        custServiceOrder.setServiceOrderId(updateOrderDto.getServiceOrderId());
        PayInfoVo payInfoVo = new PayInfoVo();
        custServiceOrder.setPayAmount(updateOrderDto.getPayAmount());

        //更新cust_service_order
        payInfoVo.setPayAmount(updateOrderDto.getPayAmount());
        if (updateOrderDto.getPayAmount() == null || updateOrderDto.getPayAmount().equals(BigDecimal.ZERO)) {
            CustServiceOrderEntity custServiceOrderEntity = custServiceOrderDao.selectByPrimaryKey(updateOrderDto.getServiceOrderId());
            if (custServiceOrderEntity.getOrderType() != 1) {
                throw new BusinessException("报价不能为空");
            }
            custServiceOrder.setPayAmount(custServiceOrderEntity.getBaojiaAmount());
            payInfoVo.setPayAmount(custServiceOrderEntity.getBaojiaAmount());
        }
        custServiceOrder.setUpdateTime(new Date());
        custServiceOrderDao.updateByPrimaryKeySelective(custServiceOrder);

        //返回支付信息
        //服务价格
        SysServiceEntity sysServiceEntity = sysServiceDao.getByOrderType(updateOrderDto.getServiceOrderId());

        BeanUtils.copyProperties(sysServiceEntity, payInfoVo);
        //下单的服务时间
        List<CustServiceOrderTimeEntity> orderTimeEntities = custServiceOrderTimeDao.getListByOrderId(updateOrderDto.getServiceOrderId());

        //组装返回参数
        CustServiceOrderEntity custServiceOrderEntity = custServiceOrderDao.selectByPrimaryKey(updateOrderDto.getServiceOrderId());
        payInfoVo.setServicePhone(custServiceOrderEntity.getServicePhone());
        payInfoVo.setAddTime(custServiceOrderEntity.getAddTime());
        payInfoVo.setServiceAddressDetail(custServiceOrderEntity.getServiceAddressDetail());
        WxCustUser wxCustUser = wxCustUserMapper.selectByPrimaryKey(custServiceOrderEntity.getCustId());
        payInfoVo.setUserName(wxCustUser.getNickName());
        payInfoVo.setBigTypeId(sysServiceEntity.getBigTypeId());
        if (sysServiceEntity.getBigTypeId() == 1) {
            if (CollectionUtil.isNotEmpty(orderTimeEntities)) {
                int morningNum = 0;
                int afternoonNum = 0;
                int nightNum = 0;
                int allDayNum = 0;
                BigDecimal heji = new BigDecimal("0");
                for (CustServiceOrderTimeEntity orderTimeEntity : orderTimeEntities) {
                    Integer serviceOrderType = orderTimeEntity.getServiceOrderType();
                    if (serviceOrderType != null) {
                        switch (serviceOrderType) {
                            case 1: // 上午
                                morningNum = (morningNum == 0) ? 1 : morningNum + 1;
                                break;
                            case 2: // 下午
                                afternoonNum = (afternoonNum == 0) ? 1 : afternoonNum + 1;
                                break;
                            case 3: // 夜宵
                                nightNum = (nightNum == 0) ? 1 : nightNum + 1;
                                break;
                            case 4: // 全天
                                allDayNum = (allDayNum == 0) ? 1 : allDayNum + 1;
                                break;
                        }
                    }
                }
                payInfoVo.setMorningNum(morningNum);
                payInfoVo.setAfternoonNum(afternoonNum);
                payInfoVo.setNightNum(nightNum);
                payInfoVo.setAllDayNum(allDayNum);

                heji = payInfoVo.getMorningAmount().multiply(BigDecimal.valueOf(morningNum))
                        .add(payInfoVo.getAfternoonAmount().multiply(BigDecimal.valueOf(afternoonNum)))
                        .add(payInfoVo.getNightAmount().multiply(BigDecimal.valueOf(nightNum)))
                        .add(payInfoVo.getAllDayAmount().multiply(BigDecimal.valueOf(allDayNum)));
                payInfoVo.setHeji(heji);
                payInfoVo.setServiceOrderId(updateOrderDto.getServiceOrderId());
                return payInfoVo;
            }
        } else if (sysServiceEntity.getBigTypeId() == 2) {
            payInfoVo.setMinPerson(sysServiceEntity.getMinPerson());
            payInfoVo.setMaxPerson(sysServiceEntity.getMaxPerson());
            payInfoVo.setServiceName(sysServiceEntity.getServiceName());
            payInfoVo.setHeji(sysServiceEntity.getMinAmount());
            payInfoVo.setServiceOrderId(updateOrderDto.getServiceOrderId());
            return payInfoVo;
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object deleteOrder(Long serviceOrderId) {
        //判断订单是否是己取消
        CustServiceOrderEntity custServiceOrderEntity = custServiceOrderDao.selectByPrimaryKey(serviceOrderId);
        if (custServiceOrderEntity.getOrderState() != 7) {
            return "订单状态异常";
        } else {
            //删除cust_service_order
            custServiceOrderDao.deleteByPrimaryKey(serviceOrderId);

            //删除cust_service_order_chef
            CustServiceOrderChefEntity chefEntity = new CustServiceOrderChefEntity();
            chefEntity.setServiceOrderId(serviceOrderId);
            custServiceOrderChefDao.delete(chefEntity);

            //删除cust_service_order_url
            CustServiceOrderUrlEntity custServiceOrderUrlEntity = new CustServiceOrderUrlEntity();
            custServiceOrderUrlEntity.setServiceOrderId(serviceOrderId);
            custServiceOrderUrlDao.delete(custServiceOrderUrlEntity);

            //删除cust_service_order_time
            CustServiceOrderTimeEntity custServiceOrderTimeEntity = new CustServiceOrderTimeEntity();
            custServiceOrderTimeEntity.setServiceOrderId(serviceOrderId);
            custServiceOrderTimeDao.delete(custServiceOrderTimeEntity);
            return "删除成功";
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirmServiceOrder(Long serviceOrderId) {
        //更新状态
        CustServiceOrderEntity custServiceOrder = new CustServiceOrderEntity();
        custServiceOrder.setServiceOrderId(serviceOrderId);
        custServiceOrder.setOrderState(6);
        custServiceOrder.setUpdateTime(new Date());
        custServiceOrderDao.updateByPrimaryKeySelective(custServiceOrder);

        CustServiceOrderEntity custServiceOrderEntity = custServiceOrderDao.selectByPrimaryKey(serviceOrderId);

        //更新接单师傅余额
        BigDecimal amount = custServiceOrderEntity.getTrueAmount();
        amount = amount.multiply(BigDecimal.ONE.subtract(custServiceOrderEntity.getPingtaiBili().divide(BigDecimal.valueOf(10000))));
        wxCustUserMapper.updateAmount(amount, custServiceOrderEntity.getChefId());


        CustFlowTypeEntity cfte2 = custFlowTypeDao.selectByPrimaryKey(2L);
        WxCustUser wc2 = wxCustUserMapper.selectByPrimaryKey(custServiceOrderEntity.getChefId());
        //插入cust_flow
        CustFlowEntity custFlowEntity = new CustFlowEntity();
        custFlowEntity.setCustId(custServiceOrderEntity.getChefId());
        custFlowEntity.setType(cfte2.getType());
        custFlowEntity.setFlowTypeName(cfte2.getFlowTypeName());
        custFlowEntity.setFlowTypeId(cfte2.getFlowTypeId());
        custFlowEntity.setFee(amount);
        custFlowEntity.setFeeBefore(wc2.getBalanceAmount());
        custFlowEntity.setFeeAfter(wc2.getBalanceAmount().add(amount));
        custFlowEntity.setAddTime(new Date());
        custFlowEntity.setServiceOrderId(serviceOrderId);
        custFlowDao.insert(custFlowEntity);


        //查询下，是否是新的店铺
        Integer num = custServiceOrderDao.getNumByCustId(custServiceOrderEntity.getCustId(), custServiceOrderEntity.getChefId());
        WxCustUser custUser = wxCustUserMapper.selectByPrimaryKey(custServiceOrderEntity.getChefId());

        //更新接单总量和合作店铺
        WxCustUser wc = new WxCustUser();
        wc.setCustId(custServiceOrderEntity.getChefId());
        wc.setTodayAmount(custUser.getTodayAmount().add(amount));
        wc.setJiedanNum(custUser.getJiedanNum() + 1);
        wc.setHezuoNum(custUser.getHezuoNum() + (num == 1 ? num : 0));
        wc.setUpdateTime(new Date());
        wxCustUserMapper.updateByPrimaryKeySelective(wc);


        //分享赚
        if (!"0".equals(custServiceOrderEntity.getShareCustId().toString())) {
            BigDecimal shareAmount = custServiceOrderEntity.getTrueAmount().subtract(amount).multiply(custServiceOrderEntity.getShareBili().divide(BigDecimal.valueOf(10000)));
            wxCustUserMapper.updateAmount(shareAmount, custServiceOrderEntity.getShareCustId());

            CustFlowTypeEntity cfte1 = custFlowTypeDao.selectByPrimaryKey(3L);
            WxCustUser wc1 = wxCustUserMapper.selectByPrimaryKey(custServiceOrderEntity.getShareCustId());
            //收支明细
            CustFlowEntity cfe = new CustFlowEntity();
            cfe.setCustId(custServiceOrderEntity.getShareCustId());
            cfe.setType(cfte1.getType());
            cfe.setFlowTypeName(cfte1.getFlowTypeName());
            cfe.setFlowTypeId(cfte1.getFlowTypeId());
            cfe.setFee(shareAmount);
            cfe.setFeeBefore(wc1.getBalanceAmount());
            cfe.setFeeAfter(wc1.getBalanceAmount().add(amount));
            cfe.setAddTime(new Date());
            cfe.setServiceOrderId(serviceOrderId);
            custFlowDao.insert(cfe);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pickChef(Long serviceOrderId, Long chefId) {
        //把该师傅改成选择，其他师傅改成拒绝
        custServiceOrderChefDao.orderChefState(serviceOrderId, chefId);

        //更新cust_service_order
        CustServiceOrderEntity custServiceOrderEntity = new CustServiceOrderEntity();
        custServiceOrderEntity.setOrderState(3);
        custServiceOrderEntity.setChefId(chefId);
        custServiceOrderEntity.setServiceOrderId(serviceOrderId);
        custServiceOrderDao.updateByPrimaryKeySelective(custServiceOrderEntity);
    }

    @Override
    public void cancelYuYue(Long serviceOrderId, Long currentCustId) {
        custServiceOrderChefDao.cancelYuYue(serviceOrderId, currentCustId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleShouhou(Long serviceOrderId, Long type, String refuse) {
        //1:同意 2：拒绝
        if (type == 1) {
            //更新售后表
            CustServiceOrderShouhouEntity shouhouEntity = new CustServiceOrderShouhouEntity();
            shouhouEntity.setServiceOrderId(serviceOrderId);
            shouhouEntity.setShouhouState(2);
            shouhouEntity.setUpdateTime(new Date());
            custServiceOrderShouhouDao.updateOrderShouhou(shouhouEntity);

            CustServiceOrderEntity custServiceOrderEntity = custServiceOrderDao.selectByPrimaryKey(serviceOrderId);
            CustFlowEntity custFlowEntity = new CustFlowEntity();
            CustServiceOrderShouhouEntity serviceOrderShouhou = custServiceOrderShouhouDao.getShouhouByOrderId(serviceOrderId);
            if (custServiceOrderEntity.getPayType() == 2) {
                // 微信支付退款处理
                CustOrderPayEntity custOrderPayEntity = custOrderPayDao.getByOrderId(custServiceOrderEntity.getServiceOrderId());
                if (custOrderPayEntity.getPayState() == 7) {
                    throw new BusinessException("订单己取消！");
                }

                Long totalFee = custOrderPayEntity.getPayAmount().longValue(); // 原支付订单金额（单位：分）
                Long refundFee = serviceOrderShouhou.getShouhouAmount().longValue();

                //组装微信退款请求参数
                WxPayRefundRequest refundRequest = new WxPayRefundRequest();
                refundRequest.setOutTradeNo(custOrderPayEntity.getPayId().toString());
                refundRequest.setOutRefundNo(custOrderPayEntity.getOrderId().toString());
                refundRequest.setNotifyUrl(wxPayProperties.getRefundUrl());
                refundRequest.setTotalFee(totalFee.intValue()); // 总金额
                refundRequest.setRefundFee(refundFee.intValue()); // 退款金额
                refundRequest.setOpUserId(wxPayProperties.getMchId());

                //发起退款请求
                try {
                    WxPayRefundResult refundResult = wxPayService.refund(refundRequest);
                    if (!("SUCCESS".equals(refundResult.getResultCode()))) {
                        throw new BusinessException("微信退款失败：" + refundResult.getErrCodeDes());
                    }
                } catch (Exception e) {
                    throw new BusinessException("退款请求失败，请联系系统管理员");
                }
            }
            if (custServiceOrderEntity.getPayType() == 3) {
                //余额支付退款处理
                WxCustUser wxCustUser = wxCustUserMapper.selectByPrimaryKey(custServiceOrderEntity.getPayCustId());
                BigDecimal balanceAmount = wxCustUser.getBalanceAmount();
                wxCustUser.setBalanceAmount(balanceAmount.add(serviceOrderShouhou.getShouhouAmount()));
                custFlowEntity.setFeeBefore(balanceAmount);
                custFlowEntity.setFeeAfter(balanceAmount.add(serviceOrderShouhou.getShouhouAmount()));
                wxCustUserMapper.updateByPrimaryKeySelective(wxCustUser);
            }
            //更新custServiceOrder表
            custServiceOrderEntity.setShouhouTuiAmount(serviceOrderShouhou.getShouhouAmount());
            custServiceOrderEntity.setOrderState(10);
            custServiceOrderEntity.setShouhouTime(new Date());
            custServiceOrderEntity.setUpdateTime(new Date());
            custServiceOrderDao.updateByPrimaryKeySelective(custServiceOrderEntity);

            //新增收支明细 用户
            custFlowEntity.setCustId(custServiceOrderEntity.getPayCustId());
            custFlowEntity.setType(1);
            custFlowEntity.setFlowTypeName("获得退款");
            custFlowEntity.setFlowTypeId(9L);
            custFlowEntity.setFee(serviceOrderShouhou.getShouhouAmount());
            custFlowEntity.setServiceOrderId(custServiceOrderEntity.getServiceOrderId());
            custFlowEntity.setAddTime(new Date());
            custFlowDao.insertSelective(custFlowEntity);

            //待确认状态下给师傅结算
            if (custServiceOrderEntity.getOrderStateInitial() == 5) {
                //新增收支明细 师傅
                Long chefId = custServiceOrderEntity.getChefId();
                BigDecimal amount = custServiceOrderEntity.getTrueAmount().subtract(serviceOrderShouhou.getShouhouAmount());
                amount = amount.multiply(BigDecimal.ONE.subtract(custServiceOrderEntity.getPingtaiBili().divide(BigDecimal.valueOf(10000))));
                int result = amount.compareTo(BigDecimal.ONE);
                if (result > 0) {
                    wxCustUserMapper.updateAmount(amount, chefId);
                } else {
                    return;
                }
                //插入cust_flow
                CustFlowEntity custFlowEntity2 = new CustFlowEntity();
                custFlowEntity2.setCustId(chefId);
                custFlowEntity2.setType(1);
                custFlowEntity2.setFlowTypeName("接单收益");
                custFlowEntity2.setFlowTypeId(2L);
                custFlowEntity2.setFee(amount);
                custFlowEntity2.setAddTime(new Date());
                custFlowEntity2.setServiceOrderId(serviceOrderId);
                custFlowDao.insertSelective(custFlowEntity2);
            }

        } else {
            //更新售后表
            CustServiceOrderShouhouEntity shouhouEntity = new CustServiceOrderShouhouEntity();
            shouhouEntity.setServiceOrderId(serviceOrderId);
            shouhouEntity.setRefuse(refuse);
            shouhouEntity.setShouhouState(3);
            shouhouEntity.setUpdateTime(new Date());
            custServiceOrderShouhouDao.updateOrderShouhou(shouhouEntity);

            //更新订单表
            CustServiceOrderEntity custServiceOrderEntity = new CustServiceOrderEntity();
            custServiceOrderEntity.setServiceOrderId(serviceOrderId);
            custServiceOrderEntity.setOrderState(9);
            custServiceOrderDao.updateByPrimaryKeySelective(custServiceOrderEntity);
        }
    }
}
